import { login } from '../common/login'
const env = require('./env.js')
const request = (url, options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      method: options.method,
      url: `${env.api_host}${url}`,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': wx.getStorageSync('token')
      },
      success(request) {
        console.log(request.data)
        if (request.data.code === 0) {
          resolve(request.data)
        } else if (request.data.code === 401) {  //登录态失效
          login();
          reject(request.data)
        } else {
          reject(request.data)
        }
      },
      fail(error) {
        reject(error.data)
      }
    })
  })
}

const get = (url, options = {}) => {
  return request(url, { method: 'GET', data: options })
}

const post = (url, options) => {
  return request(url, { method: 'POST', data: options })
}

module.exports = {
  get,
  post,
}